package com.jhy.new2025.doubelpointer;

import com.jhy.suixianglu.daima20221212.ListNode;

/**
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 */
public class RemoveNthFromEnd {
    /**
     * 第一种解法
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        // 定义快慢指针
        ListNode slow = dummyNode;
        ListNode fast = dummyNode;
        for (int i = 0; i <= n; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        if (slow.next != null) slow.next = slow.next.next;

        return dummyNode.next;

    }

    /**
     * 第二种解法
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd2(ListNode head, int n) {
        // 找出链表的长度
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        int length = getLength(head);
        if (length == 0) return null;
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return dummy.next;
    }

    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            head = head.next;
            length++;
        }
        return length;
    }
}
